package com.wmlive.hhvideo.heihei.personal.activity;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cn.wmlive.hhvideo.R;

import com.wmlive.hhvideo.common.base.DcBaseActivity;
import com.wmlive.hhvideo.common.navigator.Navigator;
import com.wmlive.hhvideo.heihei.beans.login.UserInfo;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.heihei.personal.location.AmapLocationManagerImpl;
import com.wmlive.hhvideo.heihei.personal.location.LocationApi;
import com.wmlive.hhvideo.heihei.personal.location.PerfectLocation;
import com.wmlive.hhvideo.heihei.personal.presenter.PersonalInfoPresenter;
import com.wmlive.hhvideo.heihei.personal.view.IPersonalInfoView;
import com.wmlive.hhvideo.heihei.personal.widget.BirthdayDialog;
import com.wmlive.hhvideo.utils.StringUtils;
import com.wmlive.hhvideo.utils.ToastUtil;
import com.wmlive.hhvideo.utils.imageloader.GlideLoader;
import com.wmlive.hhvideo.widget.dialog.CustomDialog;

import butterknife.BindView;

/**
 * Created by XueFei on 2017/5/27.
 * <p>
 * <p>
 * 个人信息页
 */

public class PersonalInfoActivity extends DcBaseActivity<PersonalInfoPresenter> implements IPersonalInfoView {
    public static final int LOCATION_CODE = 1001;

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.et_nickname)
    EditText etNickname;
    @BindView(R.id.btn_male)
    Button btnMale;
    @BindView(R.id.btn_female)
    Button btnFemale;
    @BindView(R.id.btn_birthday)
    RelativeLayout btnBirthday;
    @BindView(R.id.tv_birthday_tip)
    TextView tvBirthdayTip;
    @BindView(R.id.tv_collensation)
    TextView tvCollensation;
    @BindView(R.id.btn_city)
    RelativeLayout btnCity;
    @BindView(R.id.iv_city)
    ImageView ivCity;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.et_sign)
    EditText etSign;

    private String name;
    private String gender;
    private String birth_day;
    private String region;
    private String description;
    private String cover_url;
    private String cover_ori;
    private String cover_ori_file_sign;
    private UserInfo userInfo;

    private boolean isEdit = false;

    private Intent intent;

    @Override
    protected PersonalInfoPresenter getPresenter() {
        return new PersonalInfoPresenter(this);
    }

    // TODO: 2017/6/2 头像上传 城市获取

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_personal_edit_info;
    }

    @Override
    protected void initData() {
        super.initData();

        intent = getIntent();
        userInfo = (UserInfo) intent.getSerializableExtra(KEY_PARAM);
        if (null != userInfo) {
            cover_url = userInfo.getCover_url();
            cover_ori = userInfo.getCover_ori();
            GlideLoader.loadCircleImage(cover_url, ivHead, R.drawable.icon_profile_bg_user_default);
            name = userInfo.getName();
            if (!TextUtils.isEmpty(name)) {
                etNickname.setText(name);
            }

            gender = userInfo.getGender();
            if (gender.equals(UserInfo.MALE)) {
                btnMale.setSelected(true);
            } else if (gender.equals(UserInfo.FEMALE)) {
                btnFemale.setSelected(true);
            } else {
                btnMale.setSelected(true);
            }

            birth_day = userInfo.getBirth_day();
            if (!TextUtils.isEmpty(birth_day)) {
                tvBirthdayTip.setText(birth_day);
                tvBirthdayTip.setTextColor(getResources().getColor(R.color.hh_color_a));

                tvCollensation.setText(StringUtils.getConstellation(StringUtils.parseYMD(birth_day)));
                tvCollensation.setTextColor(getResources().getColor(R.color.hh_color_a));
            }

            region = userInfo.getRegion();
            if (!TextUtils.isEmpty(region)) {
                tvCity.setText(region);
                tvCity.setTextColor(getResources().getColor(R.color.hh_color_a));
                ivCity.setVisibility(View.VISIBLE);
            }

            description = userInfo.getDescription();
            if (!TextUtils.isEmpty(description)) {
                etSign.setText(description);
            }
        }

        bindListener();

        getLocation();
        registerReceiver();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (null != mLocationApi) {
            mLocationApi.stopLocation();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manageActivityBroadCast) {
            unregisterReceiver(manageActivityBroadCast);
        }
        AmapLocationManagerImpl.getInstance(this).release();
    }

    private void bindListener() {
        InputFilter[] filters = new InputFilter[1];
        filters[0] = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                isEdit = true;
                int sourceLen = StringUtils.getLengthOfByteCode(source.toString());
                int destLen = StringUtils.getLengthOfByteCode(dest.toString());

                if (dstart == 0 && StringUtils.isBlackChar(source.toString())) {
                    return "";
                }

                if (dest.toString().endsWith(" ") && StringUtils.isBlackChar(source.toString())) {
                    return "";
                }

                if (dstart >= 1 && dstart <= dest.length()) {
                    String sectionStr = dest.subSequence(dstart - 1, dstart).toString();
                    if (StringUtils.isBlackChar(sectionStr) && StringUtils.isBlackChar(source.toString())) {
                        return "";
                    }
                }

                if (sourceLen + destLen > 16) {
                    ToastUtil.showToast(R.string.account_nickname_too_long);
                    try {
                        if (source.length() >= 16) {
                            return source.subSequence(0, 16);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    return "";
                }
                return source;
            }
        };
        etNickname.setFilters(filters);

        etNickname.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });

        InputFilter filter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                isEdit = true;
                int sourceLen = StringUtils.getLengthOfByteCode(source.toString());
                int destLen = StringUtils.getLengthOfByteCode(dest.toString());

                if (dstart == 0 && StringUtils.isBlackChar(source.toString()))// 第一个不能为空格
                {
                    return "";
                }

                if (dest.toString().endsWith(" ") && StringUtils.isBlackChar(source.toString()))// 不能连续两个空格
                {
                    return "";
                }

                if (dstart >= 1 && dstart <= dest.length()) {
                    String sectionStr = dest.subSequence(dstart - 1, dstart).toString();
                    if (StringUtils.isBlackChar(sectionStr) && StringUtils.isBlackChar(source.toString())) {
                        return "";
                    }
                }

                if (sourceLen + destLen > 48) {
                    ToastUtil.showToast(R.string.account_sign_too_long);
                    return "";
                }
                return source;
            }
        };
        etSign.setFilters(new InputFilter[]{filter});

        ivBack.setOnClickListener(this);
        tvSave.setOnClickListener(this);
        ivHead.setOnClickListener(this);
        btnMale.setOnClickListener(this);
        btnFemale.setOnClickListener(this);
        btnBirthday.setOnClickListener(this);
        btnCity.setOnClickListener(this);
    }

    @Override
    public void handleNetError() {
        ToastUtil.showToast(R.string.net_error);
    }

    @Override
    public void handleInfoSucceed() {
        ToastUtil.showToast(R.string.save_suc);
        dismissLoad();
        finish();
    }

    @Override
    public void handleInfoFailure(String error_msg) {
        ToastUtil.showToast(R.string.save_failure);
        dismissLoad();
        ToastUtil.showToast(error_msg);
    }

    private CustomDialog customDialog;

    @Override
    protected void onSingleClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                back();
                break;
            case R.id.tv_save:
                saveUser();
                break;
            case R.id.iv_head:
                getREADEXTERNALSTORAGE();
                break;
            case R.id.btn_male:
                if (!btnMale.isSelected()) {
                    isEdit = true;
                    btnMale.setSelected(true);
                    btnFemale.setSelected(false);
                    gender = UserInfo.MALE;
                }
                break;
            case R.id.btn_female:
                if (!btnFemale.isSelected()) {
                    isEdit = true;
                    btnMale.setSelected(false);
                    btnFemale.setSelected(true);
                    gender = UserInfo.FEMALE;
                }
                break;
            case R.id.btn_birthday:
                BirthdayDialog bd = new BirthdayDialog(this, StringUtils.parseYMD(birth_day));
                bd.setOnDatePickListener(new BirthdayDialog.OnDatePickListener() {

                    @Override
                    public void onDatePick(int year, int month, int day) {
                        isEdit = true;
                        String monthStr = "";
                        String dayStr = "";
                        if (month < 10) {
                            monthStr = "0" + String.valueOf(month);
                        } else {
                            monthStr = String.valueOf(month);
                        }
                        if (day < 10) {
                            dayStr = "0" + String.valueOf(day);
                        } else {
                            dayStr = String.valueOf(day);
                        }
                        birth_day = year + "-" + monthStr + "-" + dayStr;
                        tvBirthdayTip.setText(birth_day);
                        tvCollensation.setText(StringUtils.getConstellation(StringUtils.parseYMD(birth_day)));
                    }
                });
                bd.show();
                break;
            case R.id.btn_city:
                intent = new Intent(this, LocationActivity.class);
                startActivityForResult(intent, LOCATION_CODE);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && null != data) {
            if (requestCode == LOCATION_CODE) {
                String cityName = data.getStringExtra("city");
                region = cityName;
//                String latlng = data.getStringExtra("latlng");
                tvCity.setText(cityName);
                tvCity.setTextColor(getResources().getColor(R.color.hh_color_a));
                ivCity.setVisibility(View.VISIBLE);
            }
        }
    }

    private void saveUser() {
        if (null != userInfo) {
            name = etNickname.getText().toString();
            description = etSign.getText().toString();
            if (TextUtils.isEmpty(name)) {
                ToastUtil.showToast(R.string.user_input_nick_name_null);
                return;
            }

            loading();
            presenter.updateUser(name, gender, birth_day, region, description, cover_ori, cover_ori_file_sign);
        }
    }

    public static final String KEY_PARAM = "user";

    public static Intent getCallingIntent(Context context, UserInfo userInfo) {
        Intent intent = new Intent(context, PersonalInfoActivity.class);
        intent.putExtra(KEY_PARAM, userInfo);
        return intent;
    }

    private LocationApi mLocationApi;
    private String cityName = "";

    private void getLocation() {
        mLocationApi = createLocationApi(LocationApi.LocationMode.AMAPLOCATION);
        if(null != mLocationApi){
            PackageManager pkgManager = getPackageManager();
            boolean locationPermission =
                    pkgManager.checkPermission(Manifest.permission.ACCESS_FINE_LOCATION, getPackageName()) == PackageManager.PERMISSION_GRANTED;

            if (Build.VERSION.SDK_INT >= 23 && !locationPermission) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        0);
            } else {
                mLocationApi.startLocation(mLocationCallback);
            }
        }
    }

    //获取存取权限
    private void getREADEXTERNALSTORAGE() {
        PackageManager pkgManager = getPackageManager();
        boolean locationPermission =
                pkgManager.checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !locationPermission) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    0);
        } else {
            Navigator.getInstance().navigateToSelectPhoto(this);
        }
    }

    public LocationApi createLocationApi(LocationApi.LocationMode locationMode) {
        LocationApi locationApi = null;
        switch (locationMode) {
            case AMAPLOCATION:
                locationApi = AmapLocationManagerImpl.getInstance(this);
                break;
            default:
                break;
        }
        return locationApi;
    }

    private LocationApi.LocationCallback mLocationCallback = new LocationApi.LocationCallback() {

        @Override
        public void locationSuccess(PerfectLocation location) {
            try {
                cityName = location.cityName;
                mLocationApi.stopLocation();
                if (!region.equalsIgnoreCase(cityName)) {
                    isEdit = true;
                }
                region = cityName;
                tvCity.setText(region);
                tvCity.setTextColor(getResources().getColor(R.color.hh_color_a));
                ivCity.setVisibility(View.VISIBLE);
            } catch (IllegalStateException e) {

            }
        }

        @Override
        public void locationFailed() {
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 0 && permissions.length > 0) {
            if (permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION) {
                if (grantResults.length > 1) {
                    mLocationApi.startLocation(mLocationCallback);
                } else {
                    mLocationApi.stopLocation();
                    ToastUtil.showToast("定位权限禁止后该功能不能正常使用，请在应用程序管理中开启权限");
                }
            } else if (permissions[0] == Manifest.permission.READ_EXTERNAL_STORAGE) {
                if (grantResults.length > 1) {
                    Navigator.getInstance().navigateToSelectPhoto(this);
                } else {
                    ToastUtil.showToast("存储权限禁止后该功能不能正常使用，请在应用程序管理中开启权限");
                }
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void registerReceiver() {
        if (null == manageActivityBroadCast) {
            manageActivityBroadCast = new ManageActivityBroadCast();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UPDATE_HEAD_ACTION);
        registerReceiver(manageActivityBroadCast, intentFilter);
    }

    private ManageActivityBroadCast manageActivityBroadCast;
    public static final String UPDATE_HEAD_ACTION = "update_head";
    public static final String UPDATE_HEAD_URL_KEY = "update_head_url_key";
    public static final String UPDATE_HEAD_ORI_KEY = "update_head_ori_key";
    public static final String UPDATE_HEAD_SIGN_KEY = "update_head_sign_key";

    private class ManageActivityBroadCast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (null != intent) {
                String action = intent.getAction();
                if (action.equals(UPDATE_HEAD_ACTION)) {
                    isEdit = true;
                    String url = intent.getStringExtra(UPDATE_HEAD_URL_KEY);
                    cover_ori = intent.getStringExtra(UPDATE_HEAD_ORI_KEY);
                    cover_ori_file_sign = intent.getStringExtra(UPDATE_HEAD_SIGN_KEY);
                    GlideLoader.loadCircleImage(url, ivHead, R.drawable.icon_profile_bg_user_default);
                }
            }
        }
    }

    private void back() {
        if (isEdit) {
            customDialog = new CustomDialog(this, R.style.BaseDialogTheme);
            customDialog.setTitle(getString(R.string.dialog_personal_save_title));
            customDialog.setPositiveButton(R.string.dialog_personal_save_positive, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    customDialog.dismiss();
                    saveUser();
                }
            });
            customDialog.setNegativeButton(R.string.dialog_personal_save_negative, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    customDialog.dismiss();
                    finish();
                }
            });
            customDialog.show();
        } else {
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        back();
    }
}
